'use strict';

const checkMethod = (a, b) => {
  a = a || '';
  b = b || '';
  a = a.toUpperCase() === 'DEL' ? 'DELETE' : a.toUpperCase();
  b = b.toUpperCase() === 'DEL' ? 'DELETE' : b.toUpperCase();
  return a === b;
};

module.exports = options => {
  return async function auth(ctx, next) {
    // 设置模版的全局变量
    const whiteUrls = options.whiteUrls || [];
    const isWhiteUrl = whiteUrls.some(whiteUrl => ctx.url.startsWith(whiteUrl));

    let userId;
    const passport_type = options.passport.type;
    if (passport_type === 'session') {
      userId = ctx.session.userId;
    } else if (passport_type === 'jwt') {
      const token = ctx.request.header.authorization || ctx.cookies.get('authorization');
      const decode = token && ctx.app.jwt.verify(token, options.passport.jwtSecret);
      userId = decode && decode.userId;
    }

    if (ctx.url === '') {
      await next();
      return;
    }

    if (!isWhiteUrl) {
      if (!userId) {
        ctx.redirect('/login');
      } else {
        const { path, method } = ctx;
        //  const userId = ctx.session.userId;

        ctx.cookies.set('SameSite', 'Lax');

        const result = await ctx.model.Session.findOne({
          where: { user_id: userId }, raw: true,
        });

        const surls = result ? result.urls : [];
        const isAdmin = result ? result.isAdmin : false;

        let type;
        const allow = surls.some(surl => {
          type = surl.type;

          if (surl.url && surl.url.indexOf('/:id') > -1) {
            return checkMethod(surl.action, method) && surl.url === ctx.helper.removeArryEnd(path, '/');
          }
          return checkMethod(surl.action, method) && path === surl.url;
        });

        if (allow || isAdmin===1) await next();
        else {
          switch (type) {
          //  case 'menu':
          //  case 'page':
            case 'button':
            case 'api':
              ctx.state = 405;
              ctx.set('Content-Type', 'application/json');
              ctx.body = { code: 405, msg: '很抱歉，你无权限访问此页面或使用此功能！' };
              break;
            default:
              ctx.redirect('/error/405');
          }
        }
      }
    } else {
      await next();
    }
  };
};
